package net.oschina.aibinxiao.scheduler;

import net.oschina.aibinxiao.job.HelloJob4;
import net.oschina.aibinxiao.job.HelloJob5;
import org.quartz.*;
import org.quartz.impl.StdSchedulerFactory;

import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @Author: AiBinXiao
 * @Description: CronTrigger第一个案例，每1秒执行一次
 * @Date: 2017/10/12 9:48
 */

public class Scheduler2 {
    public static void main(String[] args) throws SchedulerException, InterruptedException{
        // 打印当前时间，格式为 yyyy-MM-dd HH:mm:ss
        Date date = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String dateStr = sdf.format(date);
        System.out.println("当前时间是：" + dateStr);

        // 创建一个JobDetail实例，将该实例与HelloJob Class绑定  传入自定义参数
        JobDetail jobDetail = JobBuilder.newJob(HelloJob5.class)
                .withIdentity("myjob1")
                .build();

        // 创建一个CronTrigger实例，每1秒触发一次任务
        CronTrigger cronTrigger = TriggerBuilder
                .newTrigger()
                .withIdentity("mytrigger1", "group1")
                .withSchedule(
                        CronScheduleBuilder
                                .cronSchedule("* * * * * ? *") // Cron表达式 *号按照顺序依次是
                )                             // [秒] [分] [小时] [日] [月] [周] [年]，*表是每
                .build();
        // 通过执行结果可以得知 endAt是优先于withRepeatCount的，endAt会覆盖withRepeatCount的效果

        // 创建Scheduler实例
        SchedulerFactory sfact = new StdSchedulerFactory();
        Scheduler scheduler = sfact.getScheduler();
        scheduler.start();
        System.out.println("Scheduled time is :" + scheduler.scheduleJob(jobDetail, cronTrigger));
        // scheduler执行2秒后挂起
        Thread.sleep(2000L);
        scheduler.shutdown(true); // shutdown不能再重新启动了
        System.out.println("scheduler is shutdown : " + scheduler.isShutdown());
    }
}
